<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item :label="v.name" :prop="v.prop" v-for="v in searchItems">
        <el-input v-if="v.type == 'input'" v-model="queryParams[v.prop]" :placeholder="'请输入' + v.name" clearable
          @keyup.enter="handleQuery" />
        <el-tree-select v-else-if="v.type == 'treeSelect'" v-model="queryParams[v.prop]" :placeholder="'请选择' + v.name"
          clearable :data="sel_option[v.prop]" :expand-on-click-node="false" :render-after-expand="false"
          @change="handleQuery" check-strictly :props="{ label: 'label' }" node-key="id" filterable />
        <el-date-picker v-else-if="v.type == 'dateTime'" v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange" :default-time="[new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 2, 1, 23, 59, 59),]" range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间"></el-date-picker>
        <el-date-picker v-else-if="v.type == 'date'" v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" :default-time="[new Date(2000, 1, 1, 0, 0, 0),
        new Date(2000, 2, 1, 23, 59, 59),]" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期"></el-date-picker>
        <el-select v-else-if="v.type == 'select'" v-model="queryParams[v.prop]" clearable filterable
          :placeholder="'请输入' + v.name" @change="handleQuery">
          <el-option v-for="item in sel_option[v.prop]" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="RefreshRight" @click="handleUpdate"
          v-hasPermi="['comlbs:simCard:synchronousData']">同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Setting" @click="setAlarm"
          v-hasPermi="['comlbs:simCard:setWarning']">设置预警</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['comlbs:simCard:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table highlight-current-row v-loading="loading" :data="simCardList" @selection-change="handleSelectionChange">
      <el-table-column :label="v.name" align="left" :prop="v.prop" v-for="v in tableItems" :width="v.width">
        <template #default="scope">
          <dict-tag v-if="v.type == 'dict'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
          <img v-else-if="v.prop == 'objIcon'" :src="myRequire('equipment/' + scope.row[v.prop] + '.png')" />
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改sim卡管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="simCardRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="流量超出预警" prop="flowAlarmValue"
          :rules="[{ required: true, message: '流量超出预警不能为空' }, { min: 50, type: 'number', message: '默认大于50' }]">
          <el-input v-model.number="form.flowAlarmValue" autocomplete="off"></el-input>
          <span style="color:red;">由天空众创运维配置，默认50M</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SimCard">
import { getConfigKey } from "@/api/system/config"
import dayjs from "dayjs"
import { listSimCard, delSimCard } from "@/api/comlbs/simCard";
import request from "@/utils/request"
import { ElLoading } from 'element-plus'
import { onActivated, watchEffect } from 'vue'
import useAppStore from "@/store/modules/app";
const { proxy } = getCurrentInstance();
const router = useRouter();

const simCardList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
const searchItems = ref([
  { name: 'SIM卡号', prop: "iccid", type: "input" },
  { name: 'SIM卡是否到期', prop: "isOutDate", type: "select" },
  { name: 'SIM卡状态', prop: "accountStatus", type: "select" },
  { name: '设备名称', prop: "numberPlate", type: "input" },
  { name: '设备号', prop: "deviceId", type: "input" },
  { name: '是否超出流量', prop: "isOutDataUsage", type: "select" },
])
const tableItems = ref([
  { name: 'SIM卡号', prop: "iccid", width: 180 },
  { name: 'SIM卡商', prop: "carrier" },
  { name: '开卡时间', prop: "activeDate" },
  { name: '到期时间', prop: "expiryDate" },
  { name: 'SIM卡总流量（M）', prop: "dataTrafficAmount" },
  { name: '剩余流量（M）', prop: "dataBalance" },
  { name: '超出流量（M）', prop: "outDataUsage" },
  { name: 'SIM卡状态', prop: "accountStatus", type: "dict" },
  { name: '设备号', prop: "deviceId" },
  { name: '设备名称', prop: "numberPlate" },
])
function myRequire(str) {
  return new URL(`../../../assets/img/${str}`, import.meta.url).href
}
const sel_option = ref({});
const dictKeys = [];
tableItems.value.forEach(v => {
  if (v.type == 'dict') {
    dictKeys.push(v.prop)
  }
});
searchItems.value.forEach(v => {
  if (v.type == 'select') {
    dictKeys.push(v.prop)
  }
});
sel_option.value = proxy.useDict.apply(this, [...dictKeys]);

/** 查询sim卡管理列表 */
function getList() {
  loading.value = true;
  listSimCard(queryParams.value).then(response => {
    simCardList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 15,
  }
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
}

/** 同步按钮操作 */
function handleUpdate() {
  proxy.$modal.confirm('是否确认同步数据？').then(function () {
    let downloadLoadingInstance = ElLoading.service({ text: "同步数据中，请稍候", background: "rgba(0, 0, 0, 0.7)", })
    request({
      url: '/comlbs/simCard/syncData',
      method: 'post'
    }).then(() => {
      getList();
      downloadLoadingInstance.close();
      proxy.$modal.msgSuccess("同步成功");
    }).catch(() => { });
  })
}

// 设置报警
function setAlarm() {
  open.value = true;
  title.value = '流量设置';
}

/** 提交按钮-报警 */
function submitForm() {
  proxy.$refs["simCardRef"].validate(valid => {
    if (valid) {
      request({
        url: '/comlbs/simCard/saveOverflowWarningConfig',
        method: 'post',
        params: {
          value: form.value.flowAlarmValue
        }
      }).then(() => {
        getList();
        proxy.$modal.msgSuccess("设置成功");
        cancel();
      }).catch(() => { });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  let length = row.id ? 1 : _ids.length
  proxy.$modal.confirm('是否确认删除这' + length + '项数据？').then(function () {
    return delSimCard(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comlbs/simCard/export',
    //@ts-ignore
    { ...queryParams.value }
    , `sim卡管理_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}

// 获取流量配置预警值
function getSetting() {
  getConfigKey('sim_out_data_usage').then(res => {
    form.value.flowAlarmValue = Number(res.msg);
  })
}
getSetting();
const appStore = useAppStore();
function handlePageQuery(firstIn) {
  // 第一次进入或者参数改变需要查询表格
  let query = appStore.pageQuery;
  if (query) {
    queryParams.value.iccid = query.iccid;
    queryParams.value.accountStatus = query.accountStatus;
    queryParams.value.deviceId = query.deviceId;
    queryParams.value.numberPlate = query.numberPlate;
    queryParams.value.isOutDate = query.isOutDate;
    queryParams.value.isOutDataUsage = query.isOutDataUsage;
    appStore.clearPageQuery();
    firstIn = true;
  }
  if (firstIn) {
    getList();
  }
}

// 解决当前已经在sim卡页面但是右上角报警筛选不生效的bug
watch(
  () => router.currentRoute.value.path,
  (newValue, oldValue) => {
    if (newValue === oldValue)
      handlePageQuery(false);
  },
  { deep: true, immediately: true }
);

onActivated(() => {
  handlePageQuery(false);
})

handlePageQuery(true);
</script>
